<?php
namespace common\models\datas;

use common\components\extenders\MenuManage;
use common\components\helpers\Fun;
use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
/**
 * Created by PhpStorm.
 * User: dongxiaofeng
 * Date: 2017/2/22
 * Time: 11:34
 */
class CustomerRegisterRelation extends \common\components\bases\BaseModel{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%customer_register_relation}}';
    }

    public function rules()
    {
        return [
            [['site_id','customer_id','mode'], 'required'],
            [['site_id', 'customer_id', 'mode'], 'integer'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => Yii::t('frontend', '自动编号'),
            'site_id' => Yii::t('frontend', '分店id'),//
            'customer_id' => Yii::t('frontend', '用户id'),//选择，缓存
            'mode' => Yii::t('frontend', '所属类型（1共同体 2综合体 3管弦乐）'),
            'created_at' => Yii::t('frontend', '创建时间'),
        ];
    }
    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };

        return $fields;
    }


    public function extraFields()
    {
        return [
            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    ['delete' => function ($data) {
                        $orders = [];
                        $site_cache  = Fun::cache('site_cache',false);
                        if($site_cache != null) {
                            foreach($site_cache as $key=>$site) {
                                if (isset($site['db'])) {
                                    $orders = (new \yii\db\Query())
                                        ->select('*')
                                        ->from('{{%orders}}')
                                        ->where(['customer_id' => $data['customer_id']])
                                        ->all(\Yii::createObject($site['db']));
                                    if (!empty($orders))
                                        break;
                                }
                            }
                        }
                        $dues = CustomerDues::find()->where(['customer_id'=>$data['customer_id']])->one();
                        $log = DepositLog::find()->where(['customer_id'=>$data['customer_id']])->one();
                        if (!empty($orders) || $dues!=null || $log!=null) {
                            return '<button class="yx-btn-disabled" type="button">删除</button>';
                        } else {
                            if(isset(\Yii::$app->user->identity->role) && \Yii::$app->user->identity->role == 'admin'){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" type="button">删除</button>';
                            }

                        }
                    },
                        'update' => function ($data) {
                            if(isset(\Yii::$app->user->identity->role) && \Yii::$app->user->identity->role == 'admin'){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" type="button">修改</button>';
                            }
                        },
                        'details'=>function(){
                            return '';
                        }
                    ]
                )->create();
            },
            'grade' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    $customergrade = Customergrade::findOne(['id'=>$cba->grade_id]);
                    return $customergrade->name;
                }else{
                    return '普通会员';
                }
            },
            'grade_id' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    $customergrade = Customergrade::findOne(['id'=>$cba->grade_id]);
                    return $customergrade->id;
                }else{
                    return 1;
                }
            },
            'account' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    return $cba['cash']?$cba['cash']:0;
                }else{
                    return 0;
                }
            },
            'scholarship_available' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    return $cba['scholarship_available']?$cba['scholarship_available']:0;
                }else{
                    return 0;
                }
            },
            'scholarship_frozen' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    return $cba['scholarship_frozen']?$cba['scholarship_frozen']:0;
                }else{
                    return 0;
                }
            },
            'deposit' => function(){
                $cba = $this->getCustomerBranchaccount();
                if(!empty($cba)){
                    return $cba['deposit']?$cba['deposit']:0;
                }else{
                    return 0;
                }
            },
            'name'=> function(){
                return isset($this->customer->name)?$this->customer->name:'';
            },
            'age'=> function(){
                return (isset($this->customer->age) && $this->customer->age > 0)?(int)date('Y')-($this->customer->age):'';
            },
            'sex'=> function(){
                if(isset($this->customer->sex)){
                    switch ($this->customer->sex){
                        case 'Male':
                            return \Yii::t('common', '男');
                        case 'Female':
                            return \Yii::t('common', '女');
                    }
                }else{
                    return '';
                }
            },
            'mobile'=>function(){
                return isset($this->customer->mobile)?$this->customer->mobile:'';
            },
            'card_id' => function(){
                return isset($this->customer->card_id)?$this->customer->card_id:'';
            },
            'is_sender' => function(){
                return (isset($this->customer->is_sender) && $this->customer->is_sender == 1)?'是':'否';
            },
            'email' => function(){
                return isset($this->customer->email)?$this->customer->email:'';
            },
            'integral' => function(){
                return isset($this->customer->integral)?$this->customer->integral:0;
            },

        ];
    }

    public function getCustomerBranchaccount(){
        $site_id = Fun::getSiteId();
        $cba = CustomerBranchaccount::findOne(['customer_id'=>$this->customer_id,'site_id'=>$site_id]);
        return $cba;
    }

    public function getCustomer(){
        return $this->hasOne(Customer::className(),['id'=>'customer_id']);
    }


    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ],
            ],

        ]);
    }
}